﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Web.Compilation;

namespace Globsite.Globalization.Mvc.DbResources
{
    public class DbResourceProvider : IResourceProvider
    {
        private IResourceReader resourceReader;
        private ResourceManager resourceManager;
        private readonly object resourceManagerSyncLock;

        public DbResourceProvider(string resourceSet, bool ignoreCase = false)
        {
            Debug.WriteLine(string.Format("DbResourceProvider.DbResourceProvider({0})", resourceSet));

            this.ResourceSet = resourceSet;
            this.IgnoreCase = ignoreCase;
            this.resourceManagerSyncLock = new object();
        }

        public string ResourceSet { get; private set; }

        public bool IgnoreCase { get; private set; }

        public IResourceReader ResourceReader
        {
            get
            {
                Debug.WriteLine(string.Format("DbResourceProvider.ResourceReader_get - resourceSet:{0}", this.ResourceSet));

                return this.resourceReader ?? (this.resourceReader = new DbResourceReader(this.ResourceSet, CultureInfo.InvariantCulture));
            }
        }

        public ResourceManager ResourceManager
        {
            get
            {
                Debug.WriteLine(string.Format("DbResourceProvider.ResourceManager_get - resourceSet:{0}", this.ResourceSet));

                if (this.resourceManager == null)
                    lock (this.resourceManagerSyncLock)
                    {
                        if (this.resourceManager == null)
                        {
                            this.resourceManager = new DbResourceManager(this.ResourceSet)
                                                    {
                                                        IgnoreCase = this.IgnoreCase
                                                    };
                        }
                    }

                return this.resourceManager;
            }
        }

        public object GetObject(string resourceKey, CultureInfo culture)
        {
            Debug.WriteLine(string.Format("DbResourceProvider.GetObject({0}, {1}) - resourceSet:{2}", resourceKey, culture, this.ResourceSet));

            if (string.IsNullOrEmpty(resourceKey))
                throw new ArgumentNullException("resourceKey");

            if (culture == null)
                culture = CultureInfo.CurrentUICulture;

            var resourceValue = this.ResourceManager.GetObject(resourceKey, culture);

            return resourceValue;
        }
    }
}
